<?php

/*
 * 依门店代码抓hybris配货单
 */

$serverFilePath =realpath(dirname(__FILE__)); ;//realpath(dirname(__FILE__)); //$_SERVER["SCRIPT_FILENAME"];
$doc_dir = strrpos($serverFilePath, ''.DIRECTORY_SEPARATOR.'crontab');
$doc_dir = substr($serverFilePath, 0, $doc_dir + 1);   //project root 
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'lib/Config.php';
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'HybrisClass.php';
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'Logging.php';
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'GaoDeAPIClass.php';

set_time_limit(0);
error_reporting(E_ALL);
header("Content-type:text/html;charset:utf-8");

$config_ini = $doc_dir . 'config/config.ini';

$ini_array = parse_ini_file($config_ini, true);
$db_array = $ini_array['DB'];
$getWebsite = $ini_array['WebSite'];
$con = mysqli_init();

mysqli_real_connect($con, $db_array['host'], $db_array['id'], $db_array['pwd'], $db_array['database'], $db_array['port']);
mysqli_set_charset($con, $db_array['encoding']);

$log = new Logging();
$log->lfile('hybris_order');

$sql = " SELECT * FROM xd_store WHERE business_status in (2,4,5) AND isdeleted=0  and zp_status = 1 ";
//$sql = " SELECT * FROM xd_store WHERE  store_id = 100081 ";
$log->lwrite('sql:'.$sql);

$result = mysqli_query($con, $sql);
$storelist = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $storelist[] = $row;
}

$log->lwrite('storelist:'.count($storelist));
$hybris=new HybrisClass($getWebsite['debug']);  # true 测试   false 正式
$h= 60*3;
$startTime=date('Y-m-d H:i:s', strtotime('-'.$h.' minute'));//date('Y-m-d').' 00:00:00';
$endTime=date('Y-m-d H:i:s');


//抓未发货的订单
$consignmentSync = "Y"; //Y为门店已确认接单,N为门店未确认接单
$acceptFlag = "N"; //Y为已确认到货,N为未确认到货
$status =$getWebsite['debug']? "READY_FOR_PICKUP" :"READY"; //READY-未发货 SHIPPED-已发货  因为hybris捡货功能未上到正式机，所以传的参数不同
foreach ($storelist as $k => $val) {
    $hybris_result=$hybris->queryZPConsignments($val['store_id'],$startTime , $endTime,$status,$consignmentSync, $acceptFlag);
//    $hybris_result=$hybris->queryZPConsignments($val['store_id'],'2020-08-01 12:11:00' , '2020-12-23 17:11:00','','', '');
//    var_dump($hybris_result);

    if (!empty($hybris_result)&& !empty($hybris_result['result'])){
        $hybris_data=$hybris_result['result'];
        if ($hybris_data['resultCode']==3 && isset($hybris_data['wsConsignmentDatas'])) {
            foreach ($hybris_data['wsConsignmentDatas'] as $value) {
                //$customre_memo = preg_replace("/\s+\r\n|`|'|\/|\\\/", "", $value['customerMemo']);
                $sellerRemarks = preg_replace("/\s+\r\n|`|'|\/|\\\/", "", $value['sellerRemarks']);
                $field = array();
                $field['shop_no']=$val['store_id'];
                $field['shop_name']=$val['storename'];
                $field['ph_no']=$value['code'];
                $field['order_no']=$value['orderCode'];
                $log->lwrite (json_encode($value, JSON_UNESCAPED_UNICODE));
                $field['source']=$value['source'];
                $field['buyer']=$value['buyer'];
                $field['receiver']=$value['receiver'];
                $field['receiver_tel']=$value['telephone'];
                $field['receiver_address']=$value['address'];
                $field['delivery_time']=$value['estimateDeliveryTime'];
                $field['customre_memo'] = $value['customerMemo'];
                $field['birthday_candles']=$value['birthdayCandles'];
                $field['actual_pay']=$value['actualPay'];
                $field['delivery_cost']=$value['deliveryCost'];
                $field['order_time']=$value['orderStartTime'];
                $field['seller_remarks'] = $sellerRemarks;
                $field['accept_flag']=$value['acceptFlag'];
                $field['consignment_sync']=$value['consignmentSync'];
                $field['hand_carrier']=$value['handCarrier'];
                $field['logistics_no']=$value['logisticsNum'];
                $field['hybris_status']=$value['status'];
                $field['ticket_no']=$value['ticketNo'];
                $field['wx_orderNo']=$value['ecsOrderId'];
//                $field['shop_delivery_time']=$value['estimateDeliveryTime'];

                $field['lng']=$value['longitude'];
                $field['lat']=$value['latitude'];
                $distance = getdistanceAction($field['lng'], $field['lat'], $val['longitude'], $val['latitude']);
                $log->lwrite ('地址：：：：：：：：：：：'.$field['lng'].'----------'.$field['lat'].'----------'.$val['longitude'].'----------'.$val['latitude'].'----------'.$distance.'：：：：：：：地址');

                $distance = round($distance,2);
                $field['distance'] = $distance;

                //商品资料, 配送方式有快递或门店配送的才保存
                if (isset($value['wsConsignmentEntryDatas'])){
                    $product_data=$value['wsConsignmentEntryDatas'];
                    $_data=array('快递','门店配送');
                    $_data_temp=array();
                    $_flag=false;
                    if (count($product_data)>0) {
                        foreach ($product_data as $pk => $pv) {
                            if (in_array($pv['dbMode'],$_data)){
                                $_flag=true;
                            }else{
                                $_data_temp[]=$pv['dbMode'];
                            }
                        }
                    }
                    if (!$_flag){  //配送方式沒有快递或门店配送
                        $log->lwrite (date('Y-m-d H:i:s')."门店:".$field['shop_no'].','.$field['ph_no'].','.$field['order_no'].'＝＞配送方式：'.json_encode($_data_temp,JSON_UNESCAPED_UNICODE));
                        continue;
                    }
                }

                $field=mysql_escape($field);
                $sql = "SELECT ph_no FROM `orders` WHERE `ph_no` = '{$field['ph_no']}' AND `shop_no` = '{$field['shop_no']}' ";
                $result = mysqli_query($con, $sql);
                if (!empty($result) && count($result) > 0) {
                    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
                }

                # 添加来源表
                $querySourceSql = "SELECT * FROM `zp_source` WHERE `source_name` = '{$value['source']}'";
                $querySourceInfo = mysqli_query($con,$querySourceSql);
                $source_row = mysqli_fetch_array($querySourceInfo, MYSQLI_ASSOC);
                if (empty($source_row)) {
                    $values_source['source_name'] = $value['source'];
                    $values_source['status'] = 1;
                    $values_source['isdeleted'] = 0;
                    $values_source = insertValue($values_source);
                    $sql_source = "INSERT INTO `zp_source` {$values_source}";
                    $result = mysqli_query($con, $sql_source);
                }

                if (empty($row)) {
                    $values = insertValue($field);
                    $sql = "INSERT INTO `orders` {$values}";
                    $result = mysqli_query($con, $sql);
                    $log->lwrite (date('Y-m-d H:i:s')."门店:".$field['shop_no'].', addorder:' . $field['ph_no'] . "\n");
                    $order_id = mysqli_insert_id($con);

                    //商品资料
                    if (isset($value['wsConsignmentEntryDatas'])){
                        $product_data=$value['wsConsignmentEntryDatas'];
                        if (count($product_data)>0) {
                            foreach ($product_data as $pk => $pv) {
                                $p_field = array();
                                $p_field['orders_id']=$order_id;
                                $p_field['ph_no'] = $field['ph_no'];
                                $p_field['product_no'] = $pv['productCode'];
                                $p_field['product_name'] = $pv['productName'];
                                $p_field['delivery_type'] = $pv['dbMode'];
                                $p_field['pastry'] = $pv['pastry'];
                                $p_field['qty'] = $pv['quantity'];
                                $p_field['unit_price'] = $pv['unitPrice'];
                                $p_field['amount'] = $pv['amount'];
                                $values = insertValue($p_field);
                                $sql = "INSERT INTO `orders_product` {$values}";
                                $result = mysqli_query($con, $sql);
                            }
                        }
                    }

                    //电子券，礼卡资料
                    if (isset($value['wsConsignmentusedTicketDatas'])){
                        $ticket_data=$value['wsConsignmentusedTicketDatas'];
                        if (count($ticket_data)>0) {
                            foreach ($ticket_data as $tk => $tv) {

                                $t_field = array();
                                $t_field['ph_no'] = $field['ph_no'];
                                $t_field['orders_id']=$order_id;
                                $t_field['card_type'] = $tv['cardType'];
                                $t_field['type_name'] = $tv['typeName'];
                                $t_field['ticket_no'] = $tv['ticketNo'];
                                $t_field['dc_bala'] = $tv['dcBala'];
                                $t_field['discount_money'] = $tv['discountMoney'];
                                $t_field['res_desc'] = $tv['resDesc'];
                                $t_field['sale_company_code'] = $tv['saleCompanyCode'];
                                $t_field['sale_store_code'] = $tv['saleStoreCode'];
                                $t_field['sale_date'] = $tv['saleDate'];
                                $values = insertValue($t_field);
                                $sql = "INSERT INTO `orders_coupon` {$values}";
                                $result = mysqli_query($con, $sql);
                            }
                        }
                    }


                } else {
                    $field = array();
                    $field['shop_no']=$val['store_id'];
                    $field['ph_no']=$value['code'];
                    $field['accept_flag']=$value['acceptFlag'];
                    $field['consignment_sync']=$value['consignmentSync'];
                    $field['hand_carrier']=$value['handCarrier'];
                    $field['logistics_no']=$value['logisticsNum'];

                    $values = updateValue($field);
                    $sql = "UPDATE `orders` set {$values}  WHERE  `ph_no` = '{$field['ph_no']}' AND `shop_no` = '{$field['shop_no']}'   ";

                    $result = mysqli_query($con, $sql);
                    if (!$result) {
                        $log->lwrite (date('Y-m-d H:i:s')."门店:".$field['shop_no'].', 更新失败:' . $field['ph_no'] .','.json_encode($field,JSON_UNESCAPED_UNICODE). "\n");
                    }
                }


            }
        }
    }else {
        $log->lwrite (date('Y-m-d H:i:s')."门店:".$val['shop_no'].', result:' . json_encode($result, JSON_UNESCAPED_UNICODE) . "\n");
    }
}
function insertValue($arr) {
    $keys = array();
    $values = array();
    foreach ($arr as $k => $val) {
        $keys[] = "`" . $k . "`";
        $values[] = "'" . $val . "'";
    }
    $ks = implode(",", $keys);
    $vals = implode(",", $values);
    $re = "(" . $ks . ", createdt) values (" . $vals . ", now())";

    return $re;
}

function updateValue($arr) {
    $result = array();
    foreach ($arr as $k => $val) {
        $result[] = "`" . $k . "`" . "='" . $val . "'";
    }
    $result[] = "`updatedt`" . "=now() ";

    $re = implode(",", $result);
    return $re;
}

 function mysql_escape($content) {
    if (!get_magic_quotes_gpc()) {

        if (is_array($content)) {
            foreach ($content as $key => $value) {
                $content[$key] = addslashes($value);
            }
        } else {
            $content = addslashes($content);
        }
    }
    return $content;
}


/**
 * 求两个已知经纬度之间的距离,单位为米
 * @param lng1 $ ,lng2 经度
 * @param lat1 $ ,lat2 纬度
 * @return float 距离，单位米
 */
function getdistanceAction($lng1, $lat1, $lng2, $lat2) {
    $radLat1 = deg2rad($lat1);
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
    return $s;
}

?>

